package main.java;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

public class Core {
	
	private static Core INSTANCE;
	
	private ArrayList<User> usersList = new ArrayList<User>();
	private User currentUser;
	private Admin admin;
	
	private Core(){}
	
	public static synchronized Core getInstance(){
		if(INSTANCE==null) INSTANCE = new Core();
		return INSTANCE;
	}
	
	public boolean logIn(String login, String password, boolean isAdmin){
		if(!isAdmin){
			for(User user : usersList){
				if(login.equals(user.getLogin()) && MD5(password).equals(user.getPassword())){
					currentUser = user;
					return true;
				}			
			}
		}
		else if(login.equals(Admin.getInstance().getLogin()) && 
				MD5(password).equals(Admin.getInstance().getPassword()))
		{
			currentUser = null;
			admin = Admin.getInstance();
			return true;
			
		}
		return false;
	}
	
	public void logOut(){
		admin = null;
		currentUser = null;
	}
	
	private String MD5(String password) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] array = md.digest(password.getBytes());
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < array.length; ++i) {
				sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
						.substring(1, 3));
			}
			return sb.toString();
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
		
	}

	public User getCurrentUser() {
		if(currentUser == null) throw new RuntimeException("There is no current user! You didn\'t log in or you logged in as Admin");
		return currentUser;
	}

	public Admin getAdmin() {
		if(admin == null) throw new RuntimeException("You didn\'t log in or you logged in as User");
		return admin;
	}

	public ArrayList<User> getUsersList() {
		return usersList;
	}
}
